import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _configure from "choerodon-ui/lib/configure";
import _Button from "choerodon-ui/pro/lib/button";
import _Form from "choerodon-ui/pro/lib/form";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _message from "choerodon-ui/lib/message";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";

/**
 * choerodon-ui - choerodon-ui 客制化配置文件
 * @Date: 2019-08-15 09:12:30
 * @LastEditTime: 2019-08-27 09:47:01
 */
import axios from 'axios';
import React, { useState } from 'react';
// import './c7n-ued-polyfill.important.less';
import intl from "./intl";
import notification from "./notification";
import { generateUrlWithGetParam, getAccessToken, getCurrentOrganizationId, isTenantRoleLevel } from "./utils";
import { getMenuId } from "./menuTab";
import { getEnvConfig } from "./iocUtils";
var jsonMimeType = 'application/json';
export var withTokenAxios = axios;

if (!withTokenAxios._CPAAS_AXIOS_IS_CONFIGED) {
  // 微前端模式下， 这个语句块会多次执行， 所以加一个条件限制， 只能执行一次
  withTokenAxios.defaults = _objectSpread(_objectSpread({}, withTokenAxios.defaults), {}, {
    headers: _objectSpread(_objectSpread({}, (withTokenAxios.defaults || {}).headers), {}, {
      // Authorization: `bearer ${getAccessToken()}`,
      'Content-Type': jsonMimeType,
      Accept: jsonMimeType,
      'X-Requested-With': 'XMLHttpRequest' // baseURL: API_HOST,

    })
  }); // Add a request interceptor

  withTokenAxios.interceptors.request.use(function (config) {
    var _config$url = config.url,
        url = _config$url === void 0 ? '' : _config$url;

    var _getEnvConfig = getEnvConfig(),
        API_HOST = _getEnvConfig.API_HOST;

    if (url.indexOf('://') === -1 && !url.startsWith('/_api')) {
      url = "".concat(API_HOST).concat(url);
    } // Do something before request is sent


    var MenuId = getMenuId();

    if (MenuId) {
      return _objectSpread(_objectSpread({}, config), {}, {
        url: url,
        headers: _objectSpread(_objectSpread({}, config.headers), {}, {
          Authorization: "bearer ".concat(getAccessToken()),
          'H-Menu-Id': "".concat(getMenuId())
        })
      });
    } else {
      return _objectSpread(_objectSpread({}, config), {}, {
        url: url,
        headers: _objectSpread(_objectSpread({}, config.headers), {}, {
          Authorization: "bearer ".concat(getAccessToken())
        })
      });
    }
  }, function (error) {
    return (// Do something with request error
      Promise.reject(error)
    );
  });
  withTokenAxios.interceptors.response.use(function (response) {
    var status = response.status,
        data = response.data;

    if (status === 204) {
      return undefined;
    }

    if (data && data.failed) {
      // notification.error({
      //   message: data.message,
      // });
      throw data;
    } else {
      return data;
    }
  });
  withTokenAxios._CPAAS_AXIOS_IS_CONFIGED = true;
} // axios.defaults.headers.common.Authorization = `bearer ${getAccessToken()}`;


_message.config({
  placement: 'bottomRight',
  bottom: 48,
  duration: 2
});

var QueryBarMore = function QueryBarMore(_ref) {
  var queryFields = _ref.queryFields,
      buttons = _ref.buttons,
      _ref$queryFieldsLimit = _ref.queryFieldsLimit,
      queryFieldsLimit = _ref$queryFieldsLimit === void 0 ? 3 : _ref$queryFieldsLimit,
      dataSet = _ref.dataSet,
      queryDataSet = _ref.queryDataSet;

  var _useState = useState(true),
      _useState2 = _slicedToArray(_useState, 2),
      hidden = _useState2[0],
      setHidden = _useState2[1];

  var handleToggle = function handleToggle() {
    setHidden(!hidden);
  };

  var query = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return dataSet.validate(false, false);

            case 2:
              if (!_context.sent) {
                _context.next = 5;
                break;
              }

              _context.next = 5;
              return dataSet.query();

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function query() {
      return _ref2.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/React.createElement("div", null, queryDataSet ? /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      marginBottom: '10px',
      alignItems: 'flex-start'
    }
  }, /*#__PURE__*/React.createElement(_Form, {
    style: {
      flex: 'auto'
    },
    columns: queryFieldsLimit,
    dataSet: queryDataSet,
    onKeyDown: function onKeyDown(e) {
      if (e.keyCode === 13) return query();
    }
  }, hidden ? queryFields.slice(0, queryFieldsLimit) : queryFields), /*#__PURE__*/React.createElement("div", {
    style: {
      marginTop: '10px',
      flexShrink: 0,
      display: 'flex',
      alignItems: 'center'
    }
  }, queryFields.length > queryFieldsLimit && /*#__PURE__*/React.createElement(_Button, {
    onClick: handleToggle
  }, hidden ? intl.get('cpaas.common.button.viewMore').d('更多查询') : intl.get('cpaas.common.button.collected').d('收起查询')), /*#__PURE__*/React.createElement(_Button, {
    onClick: function onClick() {
      queryDataSet.current.reset();
      dataSet.fireEvent('queryBarReset', {
        dataSet: dataSet,
        queryFields: queryFields
      });
    }
  }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(_Button, {
    dataSet: null,
    color: "primary",
    onClick: query
  }, intl.get('cpaas.common.button.search').d('查询')))) : null, buttons && buttons.length ? /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: 4
    }
  }, buttons) : null);
};

var lovDefineAxiosConfig = function lovDefineAxiosConfig(code) {
  var _getEnvConfig2 = getEnvConfig(),
      API_HOST = _getEnvConfig2.API_HOST,
      CPAAS_PLATFORM = _getEnvConfig2.CPAAS_PLATFORM;

  return {
    url: "".concat(API_HOST).concat(CPAAS_PLATFORM, "/v1/").concat(isTenantRoleLevel() ? "".concat(getCurrentOrganizationId(), "/") : '', "lov-view/info?viewCode=").concat(code),
    method: 'GET',
    transformResponse: [function (data) {
      // 对 data 进行任意转换处理
      var originData = {};

      try {
        originData = JSON.parse(data);
      } catch (e) {
        console.error(e, data);
        return data;
      }

      var _originData = originData,
          height = _originData.height,
          _originData$viewCode = _originData.viewCode,
          viewCode = _originData$viewCode === void 0 ? code : _originData$viewCode,
          _originData$valueFiel = _originData.valueField,
          valueField = _originData$valueFiel === void 0 ? 'value' : _originData$valueFiel,
          _originData$displayFi = _originData.displayField,
          displayField = _originData$displayFi === void 0 ? 'name' : _originData$displayFi,
          _originData$pageSize = _originData.pageSize,
          pageSize = _originData$pageSize === void 0 ? 5 : _originData$pageSize,
          _originData$queryFiel = _originData.queryFields,
          queryFields = _originData$queryFiel === void 0 ? [] : _originData$queryFiel,
          _originData$tableFiel = _originData.tableFields,
          tableFields = _originData$tableFiel === void 0 ? [] : _originData$tableFiel;
      var _originData2 = originData,
          title = _originData2.title;

      if (originData.failed) {
        title = intl.get('cpaas.common.c7n.lov.notDefine', {
          code: code
        }).d("\u503C\u96C6\u89C6\u56FE\u672A\u5B9A\u4E49: \"".concat(code, "\", \u8BF7\u7EF4\u62A4\u503C\u96C6\u89C6\u56FE!"));
      } else if (!originData.lovCode) {
        title = "lov ".concat(code, " loading...");
      }

      var lovItems = [];
      var tableWidth = 0;
      queryFields.forEach(function () {
        var queryItem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        var lovItem = {
          lovId: viewCode,
          lovItemId: "query_".concat(queryItem.field),
          gridFieldName: queryItem.field,
          gridField: 'N',
          display: queryItem.label,
          autocompleteField: 'Y',
          conditionField: 'Y',
          isAutocomplete: 'N',
          conditionFieldWidth: null,
          conditionFieldLabelWidth: null,
          conditionFieldType: queryItem.dataType,
          conditionFieldSelectCode: queryItem.dataType === 'SELECT' ? queryItem.sourceCode : null,
          conditionFieldLovCode: null,
          conditionFieldName: null,
          conditionFieldTextfield: null,
          conditionFieldNewline: 'N',
          conditionFieldSelectUrl: null,
          conditionFieldSelectVf: null,
          conditionFieldSelectTf: null,
          conditionFieldSequence: 1,
          gridFieldSequence: 1
        };
        lovItems.push(lovItem);
      });
      tableFields.forEach(function (tableItem) {
        var lovItem = {
          lovId: viewCode,
          lovItemId: "table_".concat(tableItem.dataIndex),
          gridFieldName: tableItem.dataIndex,
          gridFieldWidth: tableItem.width,
          gridFieldAlign: 'left',
          autocompleteField: 'Y',
          conditionField: 'N',
          isAutocomplete: 'N',
          gridField: 'Y',
          display: tableItem.title,
          conditionFieldWidth: null,
          conditionFieldLabelWidth: null,
          conditionFieldType: null,
          conditionFieldSelectCode: null,
          conditionFieldName: null,
          conditionFieldTextfield: null,
          conditionFieldNewline: 'N',
          conditionFieldSelectUrl: null,
          conditionFieldSelectVf: null,
          conditionFieldSelectTf: null,
          conditionFieldLovCode: null,
          conditionFieldSequence: 1,
          gridFieldSequence: 1
        };
        lovItems.push(lovItem);
        tableWidth += tableItem.width;
      });
      var queryColumns = 0;

      if (queryFields.length) {
        if (queryFields.length <= 2) {
          queryColumns = queryFields.length;
        } else {
          queryColumns = 2;
        }
      }

      return {
        originData: _objectSpread({
          lovCode: code
        }, originData),
        code: viewCode,
        title: title,
        description: title,
        lovId: viewCode,
        placeholder: title,
        sqlId: viewCode,
        customSql: null,
        queryColumns: queryColumns,
        customUrl: null,
        textField: displayField,
        valueField: valueField,
        delayLoad: 'N',
        needQueryParam: 'N',
        editableFlag: 'Y',
        canPopup: 'Y',
        lovPageSize: pageSize,
        treeFlag: 'N',
        idField: null,
        parentIdField: null,
        lovItems: lovItems,
        width: tableWidth ? tableWidth + 300 : 700,
        height: height
      };
    }]
  };
};

var lovQueryAxiosConfig = function lovQueryAxiosConfig(code) {
  var lovConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var props = arguments.length > 2 ? arguments[2] : undefined;
  var lovQueryUrl = arguments.length > 3 ? arguments[3] : undefined;

  var _ref3 = lovConfig.originData || {},
      queryUrl = _ref3.queryUrl,
      lovCode = _ref3.lovCode;

  var _getEnvConfig3 = getEnvConfig(),
      API_HOST = _getEnvConfig3.API_HOST,
      CPAAS_PLATFORM = _getEnvConfig3.CPAAS_PLATFORM;

  var url = "".concat(API_HOST).concat(CPAAS_PLATFORM, "/v1/").concat(isTenantRoleLevel() ? "".concat(getCurrentOrganizationId(), "/") : '', "lovs/data?lovCode=").concat(lovCode);

  if (lovQueryUrl) {
    url = lovQueryUrl;
  } else if (queryUrl) {
    url = generateUrlWithGetParam(queryUrl, {
      lovCode: lovCode
    });
    var organizationRe = /{organizationId}|{tenantId}/g;

    if (organizationRe.test(url)) {
      var tId = getCurrentOrganizationId();
      url = url.replace(organizationRe, tId);
    } // url = `${url}${url.indexOf('?') ? '&' : '?'}lovCode=${lovCode}`;

  }

  return {
    url: url,
    method: 'GET'
  };
}; // TODO: 批量查询lookupCode只支持独立值集，对于sql值集等的如何处理？？
// const lookupBatchAxiosConfig = codes => {
//   const url = `${API_HOST}${CPAAS_PLATFORM}/v1/${
//     isTenantRoleLevel() ? `${getCurrentOrganizationId()}/` : ''
//   }lovs/value/batch`;
//   return {
//     url,
//     method: 'GET',
//     params: codes.reduce((obj, code) => {
//       // eslint-disable-next-line
//       obj[code] = code;
//       return obj;
//     }, {}),
//   };
// };


var generatePageQuery = function generatePageQuery(_ref4) {
  var page = _ref4.page,
      pageSize = _ref4.pageSize,
      sortName = _ref4.sortName,
      sortOrder = _ref4.sortOrder;
  return {
    page: page === undefined ? page : page - 1,
    size: pageSize,
    sort: sortName && (sortOrder ? "".concat(sortName, ",").concat(sortOrder) : sortName)
  };
};

_configure({
  lookupUrl: function lookupUrl(code) {
    var _getEnvConfig4 = getEnvConfig(),
        API_HOST = _getEnvConfig4.API_HOST,
        CPAAS_PLATFORM = _getEnvConfig4.CPAAS_PLATFORM;

    return "".concat(API_HOST).concat(CPAAS_PLATFORM, "/v1/").concat(isTenantRoleLevel() ? "".concat(getCurrentOrganizationId(), "/") : '', "lovs/data?lovCode=").concat(code);
  },
  ripple: false,
  modalOkFirst: false,
  lovDefineAxiosConfig: lovDefineAxiosConfig,
  lovQueryAxiosConfig: lovQueryAxiosConfig,
  lovQueryUrl: undefined,
  // lookupBatchAxiosConfig,
  lookupAxiosMethod: 'GET',
  dataKey: 'content',
  totalKey: 'totalElements',
  axios: withTokenAxios,
  generatePageQuery: generatePageQuery,
  status: {
    add: 'create',
    update: 'update',
    delete: 'delete'
  },
  // iconfontPrefix: 'c7n',
  statusKey: '_status',
  tlsKey: '_tls',
  useColon: true,
  // eslint-disable-next-line react/jsx-props-no-spreading
  queryBar: function queryBar(props) {
    return /*#__PURE__*/React.createElement(QueryBarMore, props);
  },
  feedback: {
    loadSuccess: function loadSuccess() {},
    loadFailed: function loadFailed(resp) {
      if (resp && resp.failed) {
        notification.error({
          message: resp && resp.message
        });
      } else if (resp && resp.response) {
        var m = require("../assets/icon_page_wrong.svg");

        if (m.__esModule) {
          m = m.default;
        }

        notification.error({
          icon: /*#__PURE__*/React.createElement(React.Fragment, null),
          message: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("img", {
            src: m,
            alt: "",
            className: "ant-notification-notice-message-img"
          }), /*#__PURE__*/React.createElement("div", {
            className: "ant-notification-notice-message-content"
          }, intl.get("cpaas.common.requestNotification.".concat(resp.response.status)) || resp.message)),
          className: 'request error'
        });
      }
    },
    submitSuccess: function submitSuccess(resp) {
      notification.success({
        message: resp && resp.message
      });
    },
    submitFailed: function submitFailed(resp) {
      if (resp && resp.failed) {
        notification.error({
          message: resp && resp.message
        });
      } else if (resp && resp.response) {
        var m = require("../assets/icon_page_wrong.svg");

        if (m.__esModule) {
          m = m.default;
        }

        notification.error({
          icon: /*#__PURE__*/React.createElement(React.Fragment, null),
          message: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("img", {
            src: m,
            alt: "",
            className: "ant-notification-notice-message-img"
          }), /*#__PURE__*/React.createElement("div", {
            className: "ant-notification-notice-message-content"
          }, intl.get("cpaas.common.requestNotification.".concat(resp.response.status)) || resp.message)),
          className: 'request error'
        });
      }
    }
  },
  transport: {
    tls: function tls(_ref5) {
      var dataSet = _ref5.dataSet,
          fieldName = _ref5.name;

      // TODO: 先使用 dataSet.current 下个版本 c7n 会 把 record 传进来
      var _token = dataSet.current.get('_token');

      var _getEnvConfig5 = getEnvConfig(),
          CPAAS_PLATFORM = _getEnvConfig5.CPAAS_PLATFORM;

      return {
        url: "".concat(CPAAS_PLATFORM, "/v1/multi-language"),
        method: 'GET',
        params: {
          _token: _token,
          fieldName: fieldName
        },
        transformResponse: function transformResponse(data) {
          try {
            var jsonData = JSON.parse(data);

            if (jsonData && !jsonData.faied) {
              var tlsRecord = {};
              jsonData.forEach(function (intlRecord) {
                tlsRecord[intlRecord.code] = intlRecord.value;
              });
              return [_defineProperty({}, fieldName, tlsRecord)];
            }
          } catch (e) {// do nothing, use default error deal
          }

          return data;
        }
      };
    }
  }
});

export { withTokenAxios as axios, lovDefineAxiosConfig };